package de.arnoldmedia.mybookshelf.connector;

import java.text.MessageFormat;

import com.skype.Application;
import com.skype.Skype;
import com.skype.SkypeException;
import com.skype.Stream;

import de.arnoldmedia.mybookshelf.IMyBookshelf;
import de.arnoldmedia.mybookshelf.resources.Constants;
import de.arnoldmedia.mybookshelf.resources.ResourceHandler;

/**
 * @author aarnold
 * @date 21.02.2009
 * @version 1.0
 */
public class SkypeConnector {

	/**
	 * @category attribute cross-reference to skype application
	 */
	private Application skypeConnection = null;

	/**
	 * @category attribute Stream array of connected peers
	 */
	protected Stream[] clientsConnected = null;

	/**
	 * @category constructor
	 * @throws SkypeException
	 */
	public SkypeConnector(IMyBookshelf parent, ResourceHandler resourceHandler)
			throws SkypeException {

		Boolean debug = resourceHandler
				.getPropertyBoolean(Constants.PROPERTY_DEBUG);
		Boolean daemon = resourceHandler
				.getPropertyBoolean(Constants.PROPERTY_DAEMON);

		// set Debug mode according to global setting
		Skype.setDebug(debug);

		// set Daemon mode according to global setting
		Skype.setDaemon(daemon);

		// register application with given name and version to Skype
		// String must not contain blanks!
		this.skypeConnection = Skype.addApplication(parent.getName());

		// register listener instance to receive events
		this.skypeConnection.addApplicationListener(
				new SkypeListener(parent, this, resourceHandler));

		// get list of connected clients
		this.clientsConnected = this.skypeConnection.connectToAll();

		// TODO println debug only
		// "{0} successfully connected to Skype [debug={1}] [daemon=[{2}]"
		System.out.println(MessageFormat.format(resourceHandler
				.getPropertyString(Constants.I18N_APPLICATION_CONNECTED),
				parent.getName(), debug, daemon));

	}// SkypeConnector

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#finalize()
	 */
	@Override
	protected void finalize() throws SkypeException {
		for (Stream stream : this.clientsConnected) {
			stream.disconnect();
		}// for
	}// finalize

	/**
	 * @category method
	 * @param message
	 * @throws SkypeException
	 */
	public void sendToAll(String msg) throws SkypeException {
		for (Stream sm : this.clientsConnected) {
			sm.write(msg);
		}// for
	}// sendToAll
	
	public void sendTo(String smID, String msg) throws SkypeException {
		for (Stream sm : this.clientsConnected) {
			if (sm.getId().equalsIgnoreCase(smID)) {
				sm.write(msg);
			}//if
		}// for
	}// sendToAll
	
}// class
